app.push(function(){
    var Article = function(){
        var article = false;
        var getDataMode = 'get';
        var currentShop = 0;
        this.init = function(url){
            url = app.cloneArray(url || app.currentUrl);
            if(url[1] == 'add'){
                url[1] = 'edit';
                currentShop = url[2] + '';
                url[2] = false;
            }
            if(this[url[1]])this[url[1]](url);
            else this.showData(url[1]);
        }
        this.showData = function(id){
            mlhAPI.article.get(
            {
                id: id,
                callback: function(data){
                    app.leftMenu.hide();
                    app.main.unmask();
                    if(data['result'] == 'success'){
                        var p = 1;
                        if(data.data.element.model=='news'){
                            app.topMenu.breadcrumbList[1] = ['Новости','/category/news','news'];
                            p++;
                        }
                        if(app['category']){
                        	app.topMenu.eraseBreadcrumbList();
            				app.category.buildcategoryBreadcrumb(data.data.element['category_id'], false);
                        }
                        /*app.topMenu.breadcrumbList[p] = [data.data.element.title,'/article/'+data.data.element.article_id,'article'];
                        app.topMenu.breadcrumbList[p+1] = false;
                        app.topMenu.buildBreadcrumb();*/
        				$.tmpl( 'article_content', data.data.element).prependTo(app.elements.general_content.html(''));
        				if(data.data.element.model == 'page') return;
        				app.elements['comments'] = app.elements.general_content.find('#comments');
        				mlhAPI.article.getComments(
                        {
                            id: data.data.element.article_id,
                            callback: app.comments.showComments
                        });
                    }
                }
            })
        }
        this.news = function(){
            app.leftMenu.hide();
            mlhAPI.article.getNews(
            {
                callback: function(data){
                    app.main.unmask();
                    if(data['result'] == 'success'){
                        app.topMenu.breadcrumbList[1] = ['Новости','/news','news'];
                        app.topMenu.breadcrumbList[2] = false;
                        app.topMenu.buildBreadcrumb();
        				$.tmpl('news_content', {title : "Новости", list:data.data}).prependTo(app.elements.general_content.html(''));
                    }
                }
            });
        }
        this.edit = function(url){
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            article = url[2] ? url[2] : false;
            if(!article){
                this.build({});
                app.main.unmask();
                app.leftMenu.setEditArticleLeftMenu(article,currentShop);
            }else{
                mlhAPI.get({
                    c: 'article',
                    v: 'display',
                    id: article,
                    requestType: 'get_nc'
                },function(data){
                    console.log("Article data", data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    data.data.element['tags_count'] = data.data.element.tags.length;
                    currentShop = data.data.element['shop'];
                    this_.build(data.data.element);
                    app.topMenu.breadcrumbList[1] = ['Список статей','#article/list/' + currentShop];
                    app.topMenu.breadcrumbList[2] = [data.data.element['title'],'#article/edit/' + article];
                    app.topMenu.buildBreadcrumb();
                    app.leftMenu.setEditArticleLeftMenu(article,currentShop);
                });
            }
            if(article){
                $('#articleEditForm button[type=submit]').text('Редактировать магазин');
            }
            
        }
        this.build = function(data){
            jQuery.extend(data, {
                editMode: article!=false
            });
            var el = $.tmpl('edit_article',data);
            el.prependTo(app.elements.general_content.html(''));
            app.decorate.validateRule($('#articleEditForm input, #articleEditForm textarea, #articleEditForm select'),
            {
                success: ' ',
                endValid: function(error){
                    if(!error){
                        $('#articleEditForm .control-group').each(function(){
                            if($(this).hasClass('error')) error = true;
                            $(this).find('*[rel=req]').each(function(){
                                var value = $(this).val();
                                if(this.tagName=='SELECT' && (value==0 || value == '0') )value = false;
                                if(!value) error = true;
                            });
                        });
                    }
                    $('#articleEditForm button[type=submit]').attr('class', !error ? 'btn btn-success' : 'btn btn-warning');
                    if(!error){
                       $('#articleEditForm').find('.alert-info').show();
                       $('#articleEditForm').find('.alert[data-type=error]').hide();
                    }
                }
            });
            var newImage = false;
            app.decorate.imageForm($('#articleEditForm'), data.image, newImage , 1, {
                onFullComplete: function(){
                    newImage = true;
                }
            });
            $('#articleEditForm form').submit(function(){
                if($('#articleEditForm button[type=submit]').hasClass('btn-warning')){
                    $('#articleEditForm').find('.alert[data-type=error]').addClass('alert-error').text("Заполните все необходимые поля").show();
                    $('#articleEditForm').find('.alert-info').hide();
                    $('#articleEditForm').find('*[rel=req]').each(function(){
                        var value = $(this).val();
                        if(this.tagName=='SELECT' && (value==0 || value == '0') )value = false;
                        if(!value) {
                            $(this).parents('.control-group:first')
                                .attr('class','row control-group warning span12 no_left_margin')
                                .find('.alert:first').text('Это поле обязательно надо заполнить').show();
                            
                        }
                    });
                    return false;
                }
                var formData = {
                    callback: function(data){
                        console.log(data);
                        if(data.data['errors'] || data.data['error']){
                            var text = "";
                            if(data.data['errors']){
                                for(var k in data.data.errors){
                                    if(k=='email')$('#articleEditForm input[name=email]').parents('.control-group:first').attr('class','row control-group error');
                                    text += "<div>" + data.data.errors[k] +"</div>";
                                }
                            }else{
                                text += "<div>" + data.data['error'] +"</div>";
                            }
                            $('#articleEditForm').find('.alert[data-type=error]').addClass('alert-error').html(text).show();
                            $('#articleEditForm').find('.alert-info').hide();
                            $('#articleEditForm button[type=submit]').attr('class', 'btn btn-warning');
                        }else{
                            $('#articleEditForm').find('.alert[data-type=error]').hide();
                            //$('#articleEditForm').find('.alert-info').html(article ? 'Вы успешно отредактировали статью' : 'Вы успешно создали статью').show();
                            $('#articleEditForm button[type=submit]').attr('class', 'btn btn-success');
                            app.static.success({description:(article ? 'Вы успешно отредактировали статью' : 'Вы успешно создали статью')})
                            getDataMode = 'get_rc';
                            app.go('#article/list/' + currentShop);
                        }
                    }
                }
                if(article) formData['article_id'] = article;
                var sData = $(this).serializeArray();
                for(var i = 0; i < sData.length; i++) {
                    formData[sData[i].name] = sData[i].value;
                }
                formData['model'] = 'page';
                formData['newImage'] = newImage ? 1 : 0;
                formData['tag_id'] = $('#articleEditForm [name=tags]').getAsJSON();
                formData['shop'] = currentShop;
                console.log(formData);
                mlhAPI.article.set(formData);
                return false;
            });
           mlhAPI.category.getList({
               model:'article',
               shop_name: currentShop,
               callback: function(list){
                    console.log("Category List", list);
                    if(list.result=='error'){
                        return;
                    }
                    delete list.data['log'];
                    var select = $('#articleEditForm select[name=category_id]');
                    app.decorate.buildSelectIttems($('#articleEditForm select[name=category_id]'), {
                        list: list.data,
                        key: 'category_id',
                        active: data['category_id'],
                        multilevelKey: 'child'
                    });
                }
           });
           setTimeout(function(){
                $('#articleEditForm [name=tags]').tagsInput(
                {
                    width:'auto',
                    defaultText: '+ добавить',
                    autocomplete_url:'http://'+location.host+'/api.php?h=tag&v=autocomplete'
                });
           },300);
        }
        this.list = function(){
            var articleContainer = false;
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            if(!app.currentUrl[2]){
                app.go('#shop/list');
                return;
            }
            currentShop = app.currentUrl[2];
            app.topMenu.breadcrumbList[1] = ['Список статей','#article/list/'+currentShop];
            app.topMenu.breadcrumbList[2] = false;
            app.topMenu.buildBreadcrumb();
            app.leftMenu.setEditShopLeftMenu(currentShop);
            var el = $.tmpl('manage_article_list', 
            {
                show_select: app.user_info.user_article > 1,
                shop: currentShop
            });
            articleContainer = $(el).find('[rel=article_list]:first');
            el.prependTo(app.elements.general_content.html(''));
            mlhAPI.article.getListByShop({
                shop: currentShop,
                requestType: getDataMode,
                callback: function(data){
                    console.log(data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    articleContainer.html(data.data.info.length ? '' : 'Нет статей');
                    for(var i in data.data.info){
                        var info = data.data.info[i];
                        info['tags_count'] = info.tags.length;
                        var el = $.tmpl('manage_article_element', info);
                        el.find('.tags .koma:last').hide();
                        el.prependTo(articleContainer);
                        app.decorate.setEvents(el);
                    }
                }
            });
            getDataMode = 'get';
        }
    }
    app['article'] = new Article();
});